package com.carbohydrate42.kotlin_compose_demo.compose

import android.Manifest
import android.annotation.SuppressLint
import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import android.os.Environment
import android.provider.Settings
import android.util.Log
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.content.ContextCompat.startActivity
import com.carbohydrate42.kotlin_compose_demo.BuildConfig
import com.carbohydrate42.kotlin_compose_demo.api.FileApi
import com.carbohydrate42.kotlin_compose_demo.dto.bo.FileSearchBo
import kotlinx.coroutines.launch


@SuppressLint("UnspecifiedRegisterReceiverFlag")
fun downloadAndInstallAfterComplete(
    context: Context,
    url: String,
    fileName: String,
    onDownloadFinished: () -> Unit = {}
) {

    // 加入下载队列
    val downloadManager =
        (context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager).apply {
            enqueue(
                DownloadManager.Request(Uri.parse(url)).apply {
                    setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI)
                    setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                    setAllowedOverRoaming(false)
                    setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName)
                }
            )
        }

    // 注册监听器
    context.registerReceiver(
        object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                // 下载完成就直接安装
                if (DownloadManager.ACTION_DOWNLOAD_COMPLETE == intent.action) {
                    //获取下载ID
                    val id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
                    val uri = downloadManager.getUriForDownloadedFile(id)

                    onDownloadFinished()

                    // 直接开始安装
                    startActivity(
                        context,
                        Intent().apply {
                            action = Intent.ACTION_VIEW
                            flags = Intent.FLAG_ACTIVITY_NEW_TASK
                            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                            setDataAndType(
                                uri,
                                "application/vnd.android.package-archive"
                            )
                        },
                        null
                    )
                }
            }
        },
        IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
    )


}


@SuppressLint("UnspecifiedRegisterReceiverFlag")
fun downloadAndGoToDownloadDirectory(context: Context, url: String, fileName: String): Unit {

    // 加入下载队列
    (context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager).apply {
        enqueue(
            DownloadManager.Request(Uri.parse(url)).apply {
                setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI)
                setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                setAllowedOverRoaming(false)
                setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName)
            }
        )
    }

    // 注册监听器
    context.registerReceiver(
        object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                // 跳转到下载中心
                startActivity(
                    context,
                    Intent(DownloadManager.ACTION_VIEW_DOWNLOADS).apply {
                        flags = Intent.FLAG_ACTIVITY_NEW_TASK
                    },
                    null
                )
            }
        },
        IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
    )


}

@Preview(showBackground = true, showSystemUi = true)
@Composable
fun FileDownloadAndInstallApk() {

    val context = LocalContext.current
    val scope = rememberCoroutineScope()

    // 动态请求一下 WRITE_EXTERNAL_STORAGE 权限
    val requestPermission =
        rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
            if (isGranted) {
                Log.i("Permission: ", "Granted")
            } else {
                Log.i("Permission: ", "Denied")
            }
        }

    LaunchedEffect(Unit) {
        requestPermission.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    }


    Column {
        
        Text(text = Settings.System.getString(context.contentResolver, Settings.Secure.ANDROID_ID))

        Button(
            onClick = {
                scope.launch {
                    // 先拿一下文件的名称 (主要是后端文件下载的api较为古怪, url上看不出文件名, downloadManager 又不支持处理 response header)
                    val fileSearchBo = FileSearchBo().apply { id = 1 }
                    val fileVo = FileApi.instance.get(fileSearchBo).body()?.data

                    downloadAndGoToDownloadDirectory(
                        context,
                        "${BuildConfig.SERVER_URL}/api/file/download/${fileSearchBo.id}",
                        fileVo?.fileName ?: "unknown"
                    )
                }
            }
        ) {
            Text(text = "下载文件到系统的系统的下载目录, 并跳转到系统的下载管理器")
        }

        Button(onClick = {
            scope.launch {

                // 先拿一下文件的名称 (主要是后端文件下载的api较为古怪, url上看不出文件名, downloadManager 又不支持处理 response header)
                val fileSearchBo = FileSearchBo().apply { id = 4 }
                val fileVo = FileApi.instance.get(fileSearchBo).body()?.data

                downloadAndInstallAfterComplete(
                    context,
                    "${BuildConfig.SERVER_URL}/api/file/download/${fileSearchBo.id}",
                    fileVo?.fileName ?: "unknown"
                ) {
                    Toast.makeText(context, "下载完成准备安装", Toast.LENGTH_SHORT).show()
                }
            }
        }) {
            Text(text = "下载文件到系统的下载目录并安装APK")
        }
    }
}